package com.ruoyi.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.ruoyi.common.constant.CommonServiceConstant;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


@Configuration
public class MybatisPlusConfig {

    @Value("${yunxiang.tenant.table}")
    private String needTenantIdTables;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        System.out.println("✅ MybatisPlusInterceptor loaded!"); // 用于验证
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 1. 添加分页插件（支持 H2）
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));

        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {

            /** 当前租户 ID 的来源：ThreadLocal、Session、JWT、Header 均可 */
            @Override
            public Expression getTenantId() {
                return new LongValue(getLoginTenantId());
            }

            /** 数据库里租户字段名 */
            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean ignoreTable(String tableName) {
                // 若是用户没有登录,不做处理
                Long loginTenantId = getLoginTenantId();
                if (ObjectUtils.isEmpty(loginTenantId)){
                    return true;
                }
                // 管理员不做任何的数据隔离
                if (ObjectUtils.isNotEmpty(loginTenantId) && Objects.equals(CommonServiceConstant.ADMIN_TENANT_ID, loginTenantId)){
                    return true;
                }
                // 目前用白名单的形式
                // 系统用户, 角色, 部门, 岗位, 通知, 操作日志
                List<String> tenantTables = Arrays.asList(needTenantIdTables.split(","));
                return !tenantTables.contains(tableName.toLowerCase());

//                return "sys_dict".equalsIgnoreCase(tableName)
//                        || "sys_config".equalsIgnoreCase(tableName);
            }
        }));
        return interceptor;
    }

    private Long getLoginTenantId(){
        LoginUser loginUser = SecurityUtils.getLoginUserCanNull();
        // 若是登录用户为空，从请求中获取租户ID
        if (ObjectUtils.isEmpty(loginUser)){
            return getRequestTenantId();
        }
        if (ObjectUtils.isNotEmpty(loginUser.getUser().getTenantId())){
            return loginUser.getUser().getTenantId();
        }

        return getRequestTenantId();
    }

    private static Long getRequestTenantId() {
        ServletRequestAttributes attrs =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            // 非 web 环境（定时任务、异步线程）
            return null;
        }
        HttpServletRequest request = attrs.getRequest();
        String tenantId = (String) request.getAttribute("tenantId");
        if (ObjectUtils.isEmpty(tenantId)){
            return null;
        }
        return Long.valueOf(tenantId);
    }
}
